import React from 'react';
import { Form, Input, Icon, Button } from 'antd';
import styles from './index.less';

const MultipleInput = ({ form, prefix, initialValue, placeholder = '请输入邮箱', ...restProps }) => {
    const { getFieldDecorator } = form;

    const add = () => {
        const keys = form.getFieldValue(`${prefix}Keys`);
        const nowId = keys[keys.length - 1] + 1 || 0;
        const nextKeys = keys.concat(nowId);
        form.setFieldsValue({
            [`${prefix}Keys`]: nextKeys
        });
    };

    const remove = React.useCallback(k => {
        const keys = form.getFieldValue(`${prefix}Keys`);
        form.setFieldsValue({
            [`${prefix}Keys`]: keys.filter(key => key !== k)
        });
    }, []);

    getFieldDecorator(`${prefix}Keys`, { initialValue: initialValue || [0] });
    const keys = form.getFieldValue(`${prefix}Keys`);

    return (
        <div
            style={{
                position: 'relative'
            }}
            {...restProps}
        >
            {keys.map(key => (
                <Form.Item label="" key={key} style={{ marginBottom: 0 }}>
                    {getFieldDecorator(`${prefix}Emails[${key}]`, {
                        initialValue: '',
                        rules: [
                            {
                                required: true,
                                message: placeholder,
                                whitespace: true
                            },
                            {
                                message: '请输入正确的邮箱地址',
                                type: 'email'
                            }
                        ]
                    })(<Input placeholder={placeholder} maxLength={50} allowClear />)}
                    {keys.length > 1 && (
                        <Icon
                            type="minus-circle"
                            style={{ color: 'rgba(0,0,0,0.25)' }}
                            className={styles.delete}
                            onClick={() => remove(key)}
                        />
                    )}
                </Form.Item>
            ))}
            <Button type="dashed" block onClick={add} disabled={keys.length >= 20}>
                + 添加
            </Button>
        </div>
    );
};

export default MultipleInput;
